package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.shopping.ICartService;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import com.mall.shopping.dto.DeleteCartItemRequest;
import java.util.*;
import com.mall.shopping.dto.DeleteCartItemResponse;
import com.mall.user.constants.SysRetCodeConstants;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:05
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {
    @Reference(check = false)
    private ICartService iCartService;



    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        Long userId = createOrderContext.getUserId();
        //获取购买的购物车商品id
        List<Long> productIds = createOrderContext.getBuyProductIds();
        for (Long productId : productIds) {
            DeleteCartItemRequest deleteCartItemRequest = new DeleteCartItemRequest();
            deleteCartItemRequest.setUserId(userId);
            deleteCartItemRequest.setItemId(productId);
            DeleteCartItemResponse deleteCartItemResponse = iCartService.deleteCartItem(deleteCartItemRequest);
            //redis删除失败其实不用返回
            if (!deleteCartItemResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
                log.error("订单生成后删除购物车商品失败");
                throw new BizException("订单生成后删除购物车商品失败code未定义", "订单生成后删除购物车商品失败");
            }
        }
        return true;
    }
}
